import React, { useEffect, useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import history from 'utils/history';
import {
  Breadcrumb,
  Card,
  Radio,
  DatePicker,
  Form,
  Button,
  Table,
  Modal,
  Tag,
  Space,
  message,
  Select,
} from 'antd';
import Styles from './index.module.scss';
import { getArticleList, deleteArticle } from 'api/article';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import Channel from 'components/Channel';

const { confirm } = Modal;
const { RangePicker } = DatePicker;
//处理对应关系
const articleStatus = [
  { id: -1, name: '全部', color: 'magenta' },
  { id: 0, name: '草稿', color: 'orange' },
  { id: 1, name: '待审核', color: 'red' },
  { id: 2, name: '审核通过', color: 'green' },
  { id: 3, name: '审核失败', color: 'cyan' },
];

export default function ArticleList() {
  // 存储数据
  const [articleList, setArticleList] = useState({});
  //创建ref对象
  const configRef = useRef();

  // 封装获取列表接口
  const loadArticleList = async (config) => {
    const res = await getArticleList(config);
    console.log(res.data);
    setArticleList(res.data);
  };
  // 发请求
  useEffect(() => {
    loadArticleList();
  }, []);
  //按钮提交功能
  const handlerFinish = async (value) => {
    const { date, status, channel_id } = value;
    console.log(value);
    const config = { channel_id };
    if (date) {
      const begin_pubdate = date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
      config.begin_pubdate = begin_pubdate;
      config.end_pubdate = end_pubdate;
    }
    //请求参数
    if (status !== -1) {
      config.status = value.status;
    }
    console.log(config);
    //存储参数
    configRef.current = config;
    //发送请求
    loadArticleList(config);
  };
  //页码改变事件
  const handlerPageChange = async (page, per_page) => {
    //获取当前页码,并带上当前筛选后的参数
    console.log(page, per_page);
    // 发送请求
    loadArticleList({ page, per_page, ...configRef.current });
  };
  // 删除功能
  const handlerDelete = (id) => {
    console.log(id);
    //二次确认
    confirm({
      title: '提示',
      content: '是否确认删除?',
      onOk: async () => {
        //执行发送请求代码
        await deleteArticle(id);
        //刷新界面,将原本的参数带上
        loadArticleList({
          ...configRef.current,
          page: articleList.page,
          per_page: articleList.per_page,
        });
        message.success('删除成功');
      },
    });
  };

  // 表格表头数据
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      width: 150,
      align: 'center',
      render: (item) => {
        if (!item.images.length)
          return (
            <img style={{ width: 150 }} src={require('assets/logo.png')}></img>
          );
        if (item.type === 3) {
          return item.images.map((pic) => {
            return (
              <img
                key={pic}
                style={{ width: 100, marginTop: 6 }}
                src={pic}
              ></img>
            );
          });
        }
        return <img style={{ width: 150 }} src={item.images}></img>;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        // find方法  返回通过的第一个对象
        const info = articleStatus.find((item) => {
          return item.id === value;
        });
        return <Tag color={info.color}>{info.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text, record) => {
        return (
          <Space>
            <Button
              type="primary"
              shape="circle"
              onClick={() => history.push('/edit/' + record.id)}
              icon={<EditOutlined />}
            ></Button>
            <Button
              type="primary"
              shape="circle"
              danger
              onClick={() => {
                handlerDelete(record.id);
              }}
              icon={<DeleteOutlined />}
            ></Button>
          </Space>
        );
      },
    },
  ];

  return (
    <div className={Styles.articleList}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <a href="">文章列表</a>
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          onFinish={handlerFinish}
          initialValues={{ status: -1, channel_id: 0 }}
        >
          <Form.Item label="状态" name="status">
            {/* 单选框 */}
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Channel></Channel>
          </Form.Item>
          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <div>根据筛选结果共查询到{articleList.total_count}条结果:</div>
        <Table
          columns={columns}
          dataSource={articleList.results}
          rowKey="id"
          pagination={{
            total: articleList.total_count,
            onChange: handlerPageChange,
          }}
        />
      </Card>
    </div>
  );
}
